import { createSubscription } from "./utils/Subscription"
import ControllerProxy from "./ControllerProxy"
import CameraModule from "./module/CameraModule"
import CameraPoseData from "./object/CameraPoseData"
interface proxiesItem {
  controller: ControllerProxy
  requester: any
}
export default class CameraPoseProxy {
  controller: CameraModule
  data: CameraPoseData
  proxies: proxiesItem[]
  constructor(e: CameraModule, t: CameraPoseData) {
    this.controller = e
    this.data = t
    this.proxies = []
  }
  get pose() {
    return this.data
  }
  activeSession(e: ControllerProxy) {
    if (0 === this.proxies.length) return !1
    return this.proxies[this.proxies.length - 1].controller === e
  }
  newSession(e: { onAccessGranted: any }) {
    let t = null
    if (-1 !== this.proxies.findIndex(t => t.requester === e)) throw new Error("Cannot create two sessions with the same requester")
    return createSubscription(
      () => {
        if (!t) {
          if (this.proxies.length > 0) {
            const e = this.proxies[this.proxies.length - 1]
            e.requester.onAccessRevoked(e.controller)
          }
          t = new ControllerProxy(this, this.controller)
          this.proxies.push({ controller: t, requester: e })
          e.onAccessGranted(t)
        }
      },
      () => {
        if (t) {
          const e = this.proxies.findIndex(e => e.controller === t)
          if (-1 !== e) {
            const t = this.proxies[e],
              i = e === this.proxies.length - 1
            i && t.requester.onAccessRevoked(t.controller)
            this.proxies.splice(e, 1)
            if (this.proxies.length > 0 && i) {
              const e = this.proxies[this.proxies.length - 1]
              e.requester.onAccessGranted(e.controller)
            }
          }
        }
      }
    )
  }
}
